package com.wf.smartcomm.server.weixin.action;


import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.wf.smartcomm.server.bean.House;
import com.wf.smartcomm.server.bean.UnLock;
import com.wf.smartcomm.server.bean.UnitMachine;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.client.action.BaseAction;
import com.wf.smartcomm.server.model.Page;
import com.wf.smartcomm.server.model.PushMessage;
import com.wf.smartcomm.server.push.Pusher;
import com.wf.smartcomm.server.service.HouseService;
import com.wf.smartcomm.server.service.UnitMachService;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.PushUtils;
import com.wf.smartcomm.server.weixin.util.WeixinUtil;

@Controller("weixinUnlockAction")
@Scope("prototype")
public class UnlockAction extends BaseAction {
	
	@Resource
	private UserService userServiceImpl;
	
	@Resource
	private UnitMachService unitServiceImpl;
	
	@Resource
	private HouseService houseServiceImpl;

	
	private static Logger logger = Logger.getLogger(UnlockAction.class);
	
	public String getUnlock(){
		String returnType="unlock";
		String openId="";
//		request.setAttribute("returnType", returnType);
//		return "login"; 
		//从session中取openId
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if (user != null) {
//			Cookie cookie = new Cookie("userId", user.getObjectId());
//			cookie.setMaxAge(3600*24*30*12*2);
//			response.addCookie(cookie);
			houseServiceImpl.listUnlockHouses(user, page);
			if (page.getDataList() != null && page.getDataList().size() > 0) {
				List<UnitMachine> unitMachines = new ArrayList<UnitMachine>();
				Page page2 = new Page();
				for (House house : (List<House>)page.getDataList()) {
					unitServiceImpl.listByHouse(house, page2);
					unitMachines.addAll((List<UnitMachine>)page2.getDataList());
				}
				
				request.setAttribute("ums", unitMachines);
			}
			return "success";
		}else {
			String code = request.getParameter("code");
			logger.info("code--------->"+code);
			String oauth_full_url ="";
			if (PushUtils.isDevEnv) {
				oauth_full_url=oauth_base_url_dev+"&code="+code+"&grant_type=authorization_code";
			}else {
				oauth_full_url=oauth_base_url_gen+"&code="+code+"&grant_type=authorization_code";
			}
			
			JSONObject jsonObject = WeixinUtil.httpRequest(oauth_full_url, "GET", null);
			if (jsonObject != null) {
				logger.info(jsonObject);
				openId = jsonObject.getString("openid");
				logger.info("openId-------->:"+openId);
				user = userServiceImpl.getUserByOpenId(openId);
				if (user == null) {
//					Cookie cookie = new Cookie("openId", openId);
//					cookie.setMaxAge(3600*24*30*12*2);
//					response.addCookie(cookie);
					request.setAttribute("returnType", returnType);
					request.setAttribute("openId", openId);
					return "login";
				}
				session.setAttribute("user", user);
//				Cookie cookie = new Cookie("userId", user.getObjectId());
//				cookie.setMaxAge(3600*24*30*12*2);
//				response.addCookie(cookie);
				houseServiceImpl.listUnlockHouses(user, page);
				if (page.getDataList() != null && page.getDataList().size() > 0) {
					House house = (House) page.getDataList().get(0);
					unitServiceImpl.listByHouse(house, page);
					request.setAttribute("ums", page.getDataList());
				}
				return "success";
			}else {
				logger.info("jsonObject is null");
				request.setAttribute("returnType", returnType);
				request.setAttribute("openId", openId);
				return "login";
			}
		}
	}
	
	public void unlock() throws Exception{
		String mid = request.getParameter("mid");
		String uid = request.getParameter("uid");
		UnitMachine um =unitServiceImpl.getById(mid);
		User user = new User(uid);
		Pusher pusher = PushUtils.getInstance();
		PushMessage pMsg = new PushMessage();
		pMsg.setPushType(ConstantUtils.PUSH_TYPE_UNLOCK_MSG);
		boolean result = pusher.push0x20Message(um.getPushId().getBytes(), gson.toJson(pMsg).getBytes());
		pusher.close();
		if (result) {
			UnLock unlock = new UnLock();
			unlock.setUser(user);
			unlock.setUnitMachine(um);
			unlock.setType(ConstantUtils.UNLOCK_TYPE_DEFAULT);
			userServiceImpl.unlock(unlock);
			printJsonData(200);
		}else {
			printJsonData(203);
		}
	}
}
